package cn.hackertools.staticresource.controller;


import cn.hackertools.staticresource.entity.FileBodyResult;
import cn.hackertools.staticresource.entity.FileSaveBodyResult;
import cn.hackertools.staticresource.entity.FileVo;
import cn.hackertools.staticresource.entity.FileResult;
import cn.hackertools.staticresource.utils.FileHandler;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/filemember")
public class FileController {

    @Value(value = "${static-resouce-file-path}")
    private String fileRootPath;
    @Autowired
    private FileHandler fileHandler;
    @Value(value = "${static-resouce-domain}")
    private String domain;
    /**
     * 页面入口
     * @return
     */
    @RequestMapping(value = "/main")
    public ModelAndView main(String projectId){
        ModelAndView mode=new ModelAndView("file/main");
        System.out.println(File.separator);
        mode.addObject("rootPath",fileRootPath+File.separator+File.separator+projectId);
        mode.addObject("projectId",projectId);
        return mode;
    }

    @RequestMapping(value = "/getFiles")
    @ResponseBody
    public Object getFiles(FileVo fileVo){
        if(fileVo.getPath().length()<fileRootPath.length())
        {
            fileVo.setPath(fileRootPath);
        }
        FileResult fileResult=new FileResult();
        List<FileResult.ListBean> listBeans = fileHandler.readFiles(fileVo.getPath(),fileVo.getSearch(),fileVo.getAll());
        fileResult.setList(listBeans);
        String page= "<div><span class='Pcurrent'>1</span><span class='Pnumber'>1/1</span><span class='Pline'>从1-"+listBeans.size()+"条</span><span class='Pcount'>共"+listBeans.size()+"条数据</span></div>" ;
        fileResult.setPage(page);

        fileResult.setPATH(fileVo.getPath());
        fileResult.setFile_recycle(true);
        List<FileResult.StoreBean> store=new ArrayList<>();
        FileResult.StoreBean storeBean=new FileResult.StoreBean();
        storeBean.setData(new ArrayList<>());
        storeBean.setName("默认分类");
        store.add(storeBean);
        fileResult.setStore(store);
        return fileResult;
    }

    @RequestMapping(value = "/readFile")
    @ResponseBody
    public Object readFile(String path)
    {
        FileBodyResult fileBodyResult=new FileBodyResult();
        fileBodyResult.setCaret(false);
        fileBodyResult.setEncoding("utf-8");
        fileBodyResult.setHistorys(new ArrayList<>());

        String content = fileHandler.readBody(path);
        System.out.println(content);
        if(content==null)
        {
            fileBodyResult.setStatus(false);
        }else{
            fileBodyResult.setStatus(true);
            fileBodyResult.setData(content);
        }
        return fileBodyResult;
    }

    @RequestMapping(value = "/saveFile")
    @ResponseBody
    public Object saveFile(String data,String path,String encoding)
    {
        boolean flag = fileHandler.writeFileBody(data, path, encoding);
        FileSaveBodyResult fileSaveBodyResult=new FileSaveBodyResult();
        fileSaveBodyResult.setStatus(flag);
        if(flag)
        {
            fileSaveBodyResult.setMsg("文件已保存");
        }else{
            fileSaveBodyResult.setMsg("文件失败");
        }
        fileSaveBodyResult.setHistorys(new ArrayList<>());

        return fileSaveBodyResult;
    }
    @RequestMapping(value = "/createDir")
    @ResponseBody
    public Object createDir(String path)
    {
        Map jsonObject=new HashMap<String,String>();
        File file=new File(path);
        boolean mkdir = file.mkdir();
        jsonObject.put("status", mkdir);
        if(mkdir)
        {
            jsonObject.put("msg","创建成功");
        }else{
            jsonObject.put("msg","创建失败");
        }
        return jsonObject;
    }

    @RequestMapping(value = "/createFile")
    @ResponseBody
    public Object createFile(String path)
    {
        Map jsonObject=new HashMap<String,String>();
        File file=new File(path);
        boolean mkdir = false;
        try {
        mkdir = file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
        jsonObject.put("status", mkdir);
        if(mkdir)
        {
            jsonObject.put("msg","创建成功");
        }else{
            jsonObject.put("msg","创建失败");
        }

        return jsonObject;
    }

    @RequestMapping(value = "/rename")
    @ResponseBody
    public Object renameFile(String sfile,String dfile, String rename)
    {
        Map jsonObject=new HashMap<String,String>();
        File file=new File(sfile);
        boolean mkdir = file.renameTo(new File(dfile));
        jsonObject.put("status", mkdir);
        if(mkdir)
        {
            jsonObject.put("msg","重命名成功");
        }else{
            jsonObject.put("msg","重命名失败");
        }

        return jsonObject;
    }
    @RequestMapping(value = "/delFile")
    @ResponseBody
    public Object delFile(String path)
    {

        Map jsonObject=new HashMap<String,String>();
        File file=new File(path);
        boolean mkdir = file.delete();
        jsonObject.put("status", mkdir);
        if(mkdir)
        {
            jsonObject.put("msg","删除成功");
        }else{
            jsonObject.put("msg","删除失败");
        }

        return jsonObject;
    }

    @RequestMapping(value = "/downFile")
    @ResponseBody
    public void downFile(String path, HttpServletResponse response)
    {
        try {
            FileInputStream fileInputStream=new FileInputStream(path);

            System.out.println(new File(path));
            byte[]buf=new byte[fileInputStream.available()];
            fileInputStream.read(buf);
            fileInputStream.close();
            response.reset();
            response.setContentType("text/html;charset=utf-8");
            response.addHeader("Content-type", "appllication/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename="+new String(new File(path).getName().getBytes("UTF-8"),"ISO-8859-1"));
            response.setCharacterEncoding("UTF-8");
            response.getOutputStream().write(buf);
            response.getOutputStream().flush();
            response.getOutputStream().close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @ResponseBody
    @RequestMapping(value = "/share")
    public Object share(String projectId,String path)
    {
        path=path.substring(path.indexOf("/")+1);
        String url=domain+"/share/"+projectId+"/"+path;
        System.out.println(url);
        return url;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteDir")
    public Object deleteDir(String path)
    {
        Map jsonObject=new HashMap<String,String>();
        boolean mkdir=fileHandler.deleteDir(path);
        jsonObject.put("status", mkdir);
        if(mkdir)
        {
            jsonObject.put("msg","删除成功");
        }else{
            jsonObject.put("msg","删除失败");
        }


        return jsonObject;
    }
}
